package CLIENT;

import java.io.*;
import java.net.*;
/**
 * This class responsible for the client connection and it's structure
 * @author Yaniv Kalif
 */
public class ClientConnection
{
    Socket ConnectionSocket = null;
    String _GroupIP;
    int _GroupSocket;
    ObjectOutputStream out = null;
    ObjectInputStream in = null;
    BufferedReader stdIn;
	public void Connect(String GroupIP,int GroupSocket) throws IOException
	{

		try 
		{
                        _GroupIP=GroupIP;
                        _GroupSocket=GroupSocket;
			ConnectionSocket = new Socket(_GroupIP, _GroupSocket);
                        System.out.println("Client Connected");
			//out = new PrintWriter(ConnectionSocket.getOutputStream(), true);
			//in = new BufferedReader(new InputStreamReader(ConnectionSocket.getInputStream()));
                        out = new ObjectOutputStream(ConnectionSocket.getOutputStream());
		} 
		catch (UnknownHostException e) 
		{
			System.err.println("Don't know about host.");
			System.exit(1);
		} 
		catch (IOException e) 
		{
			System.err.println("Couldn't get I/O for the connection to host.");
			System.exit(1);
		}
        }
       
        public void SendMessage(Client c, String msg) throws IOException
        {
           System.out.println("The client is sending this: " + msg);

		if ( ConnectionSocket != null && out == null)
		{
		    //out = new PrintWriter(ConnectionSocket.getOutputStream(), true); // create reader and writer
                    out = new ObjectOutputStream(ConnectionSocket.getOutputStream());
		}

		//if ( out != null ) out.println(msg);   // send msg to the server
           Message m = new Message(msg,c.GetName());
           m.SetClientsrc(c._name);

		if ( out != null )
                {
                    out.writeObject(m);   // send msg to the server
                    out.flush();
                }
        }

        public void SendID(Client c, String msg) throws IOException
        {
           System.out.println("The client is sending this: " + msg);

		if ( ConnectionSocket != null && out == null)
		{
                    out = new ObjectOutputStream(ConnectionSocket.getOutputStream());
		}
           Message m = new Message(msg,c.GetName());
           m.SetisSystemMessage(true);
          m.SetClientsrc(c._name);

		if ( out != null )
                {
                    out.writeObject(m);   // send msg to the server
                    out.flush();
                }
        }

        public Socket GetConnectedSocket(){return ConnectionSocket;}
        public void Disconnect() throws IOException
        {
            if(out!=null)
                out.close();
            if(in!=null)
            in.close();
            if(stdIn!=null)
                stdIn.close();
            if(ConnectionSocket!=null)
            ConnectionSocket.close();
        }

        
}
